import os
import threading
import subprocess

try:
    import pyttsx3
except Exception:
    pyttsx3 = None


class AudioAlert:
    def __init__(self):
        self.engine = None
        if pyttsx3 is not None:
            try:
                self.engine = pyttsx3.init()
                # 语速略慢，中文更清晰
                self.engine.setProperty('rate', 155)
            except Exception:
                self.engine = None

    def _speak_engine(self, text: str):
        try:
            self.engine.say(text)
            self.engine.runAndWait()
        except Exception:
            self.engine = None

    def _speak_espeak(self, text: str):
        try:
            subprocess.run(['espeak', text], check=False)
        except Exception:
            pass

    def speak(self, text: str):
        def run():
            if self.engine is not None:
                self._speak_engine(text)
            else:
                self._speak_espeak(text)
        threading.Thread(target=run, daemon=True).start()

    def beep(self):
        # 尝试使用系统蜂鸣（若无可回退为打印）
        try:
            # 使用 printf 触发终端蜂鸣；不保证所有终端有效
            os.system('printf "\a"')
        except Exception:
            print('[beep] 蜂鸣')